package com.example.myapplication.SuiPian;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.myapplication.Config.Content;
import com.example.myapplication.Config.OKHttpTool;
import com.example.myapplication.Config.RunOnUiThreadTool;
import com.example.myapplication.Config.TokenBean;
import com.example.myapplication.Config.User;
import com.example.myapplication.Config.ViewapteTool;
import com.example.myapplication.R;
import com.example.myapplication.ShuJu.Banner;
import com.example.myapplication.ShuJu.NewslistBean;
import com.example.myapplication.ShuJu.Re_NewsHots;
import com.example.myapplication.ShuJu.Re_NewsListbean;
import com.example.myapplication.ShuJu.Re_Servlet;
import com.example.myapplication.apter.NewsAdapter;
import com.example.myapplication.apter.NewsHotApter;
import com.example.myapplication.apter.ServerApter;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HomeFragment extends Fragment {


    private View view;
    private OkHttpClient okHttpClient;
    private Request request;
    private Handler handler;
    private ViewPager lunBo;
    private RecyclerView re_servlet;
    private Gson gson;
    private ArrayList<View> reyuan_list;
    private View re1;
    private View re2;
    private View re3;
    private String TAG = "TAG";
    private TabLayout tab_new;
    private JSONObject jsonObject;
    private Content content;
    private RequestBody requestBody;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        ivitview();
        view = inflater.inflate(R.layout.fragment_home, container, false);
        // ban_img = view.findViewById(R.id.ban_img);
        re_servlet = view.findViewById(R.id.re_servlet);
        tab_new = view.findViewById(R.id.tab_new);

        //判断是否登录过
        islogin();

        //轮播图数据
        getBannerDate();
        //添加圆点给轮播图
        getYuan();
        //全部服务
        getservice();
        //获取新闻列表
        Newslist();
        getNewDate(13);
        //热门主题
        getHotDate();
        return view;
    }

    private void islogin() {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("login", Context.MODE_PRIVATE);
        String token = sharedPreferences.getString("token", "");

        if(!"".equals(token)){
            OKHttpTool.TOKEN=token;
            TokenBean.token=token;
        }

    }

    private void Newslist() {
        OKHttpTool.doNetRequest("prod-api/api/park/press/category/list",
                OKHttpTool.GET,
                NewslistBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        RunOnUiThreadTool.run(HomeFragment.this.getActivity(), new RunOnUiThreadTool.RunCallback() {
                            @Override
                            public void set() {
                                NewslistBean newslistBean = (NewslistBean) obj;
                                if (newslistBean.getCode() == 200) {
                                    for (NewslistBean.DataBean datum : newslistBean.getData()) {
                                        TabLayout.Tab tab = tab_new.newTab();
                                        tab.setText(datum.getName());
                                        tab_new.addTab(tab);
                                    }
                                    Getnewslist(newslistBean);
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void Getnewslist(NewslistBean newslistBean) {
        tab_new.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                String tabtext = tab.getText().toString();
                if (newslistBean.getData().get(position).getName().equals(tabtext)) {
                    //新闻列表
                    getNewDate(newslistBean.getData().get(position).getId());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void getYuan() {
        reyuan_list = new ArrayList<>();
        re1 = view.findViewById(R.id.re1);
        re2 = view.findViewById(R.id.re2);
        re3 = view.findViewById(R.id.re3);
        reyuan_list.add(re1);
        reyuan_list.add(re2);
        reyuan_list.add(re3);
    }

    private void getservice() {
        OKHttpTool.doNetRequest("prod-api/api/service/list",
                OKHttpTool.GET,
                Re_Servlet.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        RunOnUiThreadTool.run(HomeFragment.this.getActivity(), new RunOnUiThreadTool.RunCallback() {
                            @Override
                            public void set() {
                                Re_Servlet re_servlet = (Re_Servlet) obj;
                                if (re_servlet.getCode() == 200) {
                                    binServer(re_servlet);
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });

    }

    private void binServer(Re_Servlet servlet) {
        //适配器
        //ridLayoutManager 是 Android 中的一种布局管理器，用于在 RecyclerView 中展示网格布局。它将项目以网格状的形式进行排列，并提供了灵活的跨行和跨列功能。
        ServerApter serverApter = new ServerApter(getContext(), servlet.getRows());
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 5);
        re_servlet.setLayoutManager(gridLayoutManager);
        re_servlet.setAdapter(serverApter);
    }

    private void ivitview() {
        gson = new Gson();
        handler = new Handler();
        okHttpClient = new OkHttpClient();

        jsonObject = new JSONObject();
        try {
            jsonObject.put("username", User.USERNAME);
            jsonObject.put("password", User.PWD);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void getBannerDate() {
        OKHttpTool.doNetRequest("prod-api/api/rotation/list",
                OKHttpTool.GET,
                Banner.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        RunOnUiThreadTool.run(HomeFragment.this.getActivity(), new RunOnUiThreadTool.RunCallback() {
                            @Override
                            public void set() {
                                Banner banner = (Banner) obj;
                                if (banner.getCode() == 200) {
                                    // binBannerDate(list_banner);
                                    ArrayList<String> strings = new ArrayList<>();
                                    for (Banner.RowsDTO row : banner.getRows()) {
                                        strings.add(row.getAdvImg());

                                    }
                                    lunBo = view.findViewById(R.id.lunbo);
                                    ViewapteTool viewapteTool = new ViewapteTool(HomeFragment.this.getContext(), strings);
                                    lunBo.setAdapter(viewapteTool);
                                    mHandler.sendEmptyMessageDelayed(0, 3 * 1000);
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void binBannerDate() {
        /*banner插件*/
        /*ban_img.setAdapter(new BannerImageAdapter(list_banner) {
            @Override
            public void onBindView(Object o, Object o2, int i, int i1) {
                BannerImageHolder bannerImageHolder = (BannerImageHolder)o;
                Glide.with(getContext()).load(list_banner.get(i).getAdvImg()).into(bannerImageHolder.imageView);
            }
        });
        ban_img.setIndicator(new CircleIndicator(getContext()));*/
        lunBo.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < reyuan_list.size(); i++) {
                    reyuan_list.get(i).setBackground(view.getContext().getDrawable(R.drawable.re_hou));
                }
                reyuan_list.get(position).setBackground(view.getContext().getDrawable(R.drawable.re_hei));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    private void getNewDate(Integer id) {
        OKHttpTool.doNetRequest("prod-api/api/park/press/press/list?type=" + id,
                OKHttpTool.GET,
                Re_NewsListbean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        RunOnUiThreadTool.run(HomeFragment.this.getActivity(), new RunOnUiThreadTool.RunCallback() {
                            @Override
                            public void set() {
                                Re_NewsListbean re_newsListbean = (Re_NewsListbean) obj;
                                if (re_newsListbean.getCode() == 200) {
                                    binnewdate(re_newsListbean);
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void binnewdate(Re_NewsListbean re_newsListbean) {
        RecyclerView recyclerView = view.findViewById(R.id.rcy_new);
        NewsAdapter newsApter = new NewsAdapter(getContext(), re_newsListbean.getRows());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(newsApter);
    }

    private void getHotDate() {
        OKHttpTool.doNetRequest("prod-api/press/press/list?hot=Y",
                OKHttpTool.GET,
                Re_NewsHots.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        RunOnUiThreadTool.run(HomeFragment.this.getActivity(), new RunOnUiThreadTool.RunCallback() {
                            @Override
                            public void set() {
                                Re_NewsHots re_newsHots = (Re_NewsHots) obj;
                                if (re_newsHots.getCode() == 200) {
                                    binHot(re_newsHots);
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void binHot(Re_NewsHots re_newsHots) {
        RecyclerView recyclerView = view.findViewById(R.id.rcv_hot);
        NewsHotApter newsHotApter = new NewsHotApter(getContext(), re_newsHots.getRows());
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(newsHotApter);
    }

    private void getuserToken() {
        //创建一个json的消息体
        requestBody = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json;charset=utf-8"));
        request = new Request.Builder().url("http://124.93.196.45:10001/prod-api/api/login").post(requestBody).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String json = response.body().string();
                content = gson.fromJson(json, Content.class);
                TokenBean.token = content.getToken();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }
        });
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0) {
                int index = lunBo.getCurrentItem();
                index = (index + 1) % 3;
                lunBo.setCurrentItem(index);
                mHandler.sendEmptyMessageDelayed(0, 3 * 1000);
            }
        }
    };
}




